﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.SFA.Server.Entity;
using Jumpton.Persistent;
using Jumpton.Data;
using System.Data;

namespace Jumpton.SFA.Server.BusinessRule.MasterData
{
    public class SupplyManager : BusinessLogic
    {
        public DataTable Query(decimal DomainId, string Keyword, int status)
        {
            String SQL = "DOMAIN_ID=" + DomainId;
            if (status != -1)
            {
                SQL += " AND ACTIVE=" + status;
            }
            var ot = new ObjectTable(typeof(SUPPLY), SQL, " LAST_UPDATE_TIME DESC");
            IEnumerable<DataRow> query =from supply in ot.BillDataTable.AsEnumerable()
                                        select supply;
            if (!String.IsNullOrEmpty(Keyword))
            {
               query = from supply in ot.BillDataTable.AsEnumerable()
                            where (supply.Field<String>("NAME") != null && supply.Field<String>("NAME").IndexOf(Keyword) > -1)
                             || (supply.Field<String>("ADDRESS") != null && supply.Field<String>("ADDRESS").IndexOf(Keyword) > -1)
                             || (supply.Field<String>("MOBILE") != null && supply.Field<String>("MOBILE").IndexOf(Keyword) > -1)
                             || (supply.Field<String>("TEL") != null && supply.Field<String>("TEL").IndexOf(Keyword) > -1)
                            select supply;
            }
            if (query.Count() == 0)
            {
                ot.BillDataTable.Rows.Clear();
                return ot.BillDataTable;
            }
            return query.CopyToDataTable();
        }

        public SUPPLY Load(decimal id)
        {
            return (SUPPLY)ObjectRow.Load(typeof(SUPPLY), "this.ID='" + id + "'");
        }

        

        public DataTable SelecctSupplyByChain(decimal chainID, int status)
        {
            string sql = "select * from supply where CHAIN_ID='" + chainID + "'";
            if (status != 2)
                sql += " and VALID='" + status + "'";
            return SqlData.OpenSql(sql).Tables[0];
        }

        public void DeleteSupplysInCustomerChain(decimal supplyID)
        {
            string sql = "update CUSTOMER_CHAINS set SUPPLY_ID=Null where SUPPLY_ID='" + supplyID + "'";
            SqlData.ExecuteSql(sql);
        }

      

        public void Save(SUPPLY supply)
        {
            if (supply != null)
            {
                try
                {
                   
                    supply.Save();
                }
                catch (Exception err)
                {
                    message = err.Message; 
                    throw err;

                }
            }

        }
    }
}
